class Code_2{
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int flag =0;
        ListNode head1 =l1;
        ListNode head2 =l2;
        ListNode pre = new ListNode();
        while (head1!=null && head2!=null){
            flag = sum(head1,head2,head1.val,head2.val,flag);
            pre = head1;
            head1 =head1.next;
            head2 =head2.next;
        }
        if (head1!=null ){  // l1比l2长
            while (head1.next!=null){
                flag = sum2(head1,head1.val,0,flag);
                head1 =head1.next;
            }
            flag = sum2(head1,head1.val,0,flag);
            if (flag ==1){
                head1.next = new ListNode(1);
            }
            return l1;
        }else if (head2 == null){
            if (flag ==1){
                pre.next = new ListNode(1);
            }
            return l1;
        }else { // l2比l1长
            while (head2.next!=null){
                flag = sum2(head2,0,head2.val,flag);
                head2 =head2.next;
            }
            flag = sum2(head2,0,head2.val,flag);
            if (flag ==1){
                head2.next = new ListNode(1);
            }
            return l2;
        }
    }

    public int sum(ListNode node1,ListNode node2,int x,int y,int flag){
        int sum = x + y+flag;
        if (sum>=10){
            flag=1;
            node1.val = sum %10;
            node2.val = sum %10;
        }else {
            flag=0;
            node1.val =sum;
            node2.val = sum;
        }
        return flag;
    }

    public int sum2(ListNode node1,int x,int y,int flag){
        int sum = x + y+flag;
        if (sum>=10){
            flag=1;
            node1.val = sum %10;
        }else {
            flag=0;
            node1.val =sum;
        }
        return flag;
    }
}
